<template>
  <div class="dashboard-container">
    <!-- 统计卡片 - 使用Streams.vue的紧凑设计 -->
    <el-row :gutter="8" class="stats-cards compact">
      <el-col :span="5">
        <el-card class="stat-card compact" :body-style="{ padding: '1px 8px', height: '48px', display: 'flex', alignItems: 'center', justifyContent: 'center' }">
          <div class="stat-content compact">
            <el-icon class="stat-icon compact"><VideoCamera /></el-icon>
            <div>
              <div class="stat-number compact">{{ stats.running_streams || 0 }}</div>
              <div class="stat-label compact">直播流</div>
            </div>
          </div>
        </el-card>
      </el-col>
      
      <el-col :span="5">
        <el-card class="stat-card compact" :body-style="{ padding: '1px 8px', height: '48px', display: 'flex', alignItems: 'center', justifyContent: 'center' }">
          <div class="stat-content compact">
            <el-icon class="stat-icon compact"><Film /></el-icon>
            <div>
              <div class="stat-number compact">{{ taskCounts.recording || 0 }}</div>
              <div class="stat-label compact">录制任务</div>
            </div>
          </div>
        </el-card>
      </el-col>
      
      <el-col :span="5">
        <el-card class="stat-card compact" :body-style="{ padding: '1px 8px', height: '48px', display: 'flex', alignItems: 'center', justifyContent: 'center' }">
          <div class="stat-content compact">
            <el-icon class="stat-icon compact"><Monitor /></el-icon>
            <div>
              <div class="stat-number compact">{{ taskCounts.transcoding || 0 }}</div>
              <div class="stat-label compact">转码任务</div>
            </div>
          </div>
        </el-card>
      </el-col>
      
      <el-col :span="5">
        <el-card class="stat-card compact" :body-style="{ padding: '1px 8px', height: '48px', display: 'flex', alignItems: 'center', justifyContent: 'center' }">
          <div class="stat-content compact">
            <el-icon class="stat-icon compact"><List /></el-icon>
            <div>
              <div class="stat-number compact">{{ taskCounts.segmenting || 0 }}</div>
              <div class="stat-label compact">拆条任务</div>
            </div>
          </div>
        </el-card>
      </el-col>
      
      <el-col :span="4">
        <el-card class="stat-card compact" :body-style="{ padding: '1px 8px', height: '48px', display: 'flex', alignItems: 'center', justifyContent: 'center' }">
          <div class="stat-content compact">
            <el-icon class="stat-icon compact"><Share /></el-icon>
            <div>
              <div class="stat-number compact">{{ taskCounts.forwarding || 0 }}</div>
              <div class="stat-label compact">转推任务</div>
            </div>
          </div>
        </el-card>
      </el-col>
    </el-row>

    <!-- 其余内容保持不变 -->
    <div class="system-grid">
      <!-- 左侧：服务状态 -->
      <el-card class="system-card">
        <template #header>
          <div class="card-title">
            <el-icon><Monitor /></el-icon>
            服务状态监控
          </div>
        </template>
        <div class="service-status-list">
          <div class="service-item">
            <span class="service-name">流监控服务</span>
            <span class="service-status normal">正常</span>
          </div>
          <div class="service-item">
            <span class="service-name">转码服务</span>
            <span class="service-status normal">正常</span>
          </div>
          <div class="service-item">
            <span class="service-name">抽帧服务</span>
            <span class="service-status normal">正常</span>
          </div>
          <div class="service-item">
            <span class="service-name">拆条服务</span>
            <span class="service-status normal">正常</span>
          </div>
          <div class="service-item">
            <span class="service-name">录制服务</span>
            <span class="service-status normal">正常</span>
          </div>
        </div>
      </el-card>

      <!-- 右侧：警告信息 -->
      <el-card class="system-card">
        <template #header>
          <div class="card-title">
            <el-icon><Warning /></el-icon>
            实时警告
          </div>
        </template>
        <div class="warning-list">
          <div v-if="warnings.length === 0" class="no-warning">
            <el-icon><CircleCheck /></el-icon>
            <span>暂无警告信息</span>
          </div>
          <div v-else v-for="warning in warnings" :key="warning.id" class="warning-item">
            <div class="warning-time">{{ formatTime(warning.timestamp) }}</div>
            <div class="warning-message">{{ warning.message }}</div>
          </div>
        </div>
      </el-card>
    </div>

    <!-- 直播墙 -->
    <el-card class="stream-wall-card">
      <template #header>
        <div class="card-title">
          <el-icon><VideoCamera /></el-icon>
          直播流监控墙
        </div>
      </template>
      <div class="stream-grid">
        <div 
          class="stream-item" 
          v-for="stream in paginatedStreams" 
          :key="stream.id"
        >
          <div class="stream-preview">
            <img 
              :src="stream.screenshot || '/default-screenshot.jpg'" 
              :alt="stream.name"
              class="stream-image"
            />
            <div class="stream-status-badge" :class="stream.status">
              {{ stream.status === 'online' ? '在线' : '离线' }}
            </div>
          </div>
        </div>
      </div>
      
      <div class="pagination-container">
        <el-pagination
          v-model:current-page="currentPage"
          :page-size="pageSize"
          :total="totalStreams"
          layout="prev, pager, next, jumper"
          :pager-count="5"
          @current-change="handlePageChange"
        />
      </div>
    </el-card>
  </div>
</template>

<script setup>
import { ref, onMounted, computed } from 'vue'
import { VideoCamera, List, Film, Monitor, Refresh, Warning, CircleCheck, Share } from '@element-plus/icons-vue'
import streamApi from '@/api/stream'

// 响应式数据
const loading = ref(false)
const stats = ref({})
const taskCounts = ref({})
const streams = ref([])
const warnings = ref([])

// 分页数据
const currentPage = ref(1)
const pageSize = 16 // 4×4网格

// 计算属性 - 分页流
const totalStreams = computed(() => streams.value.length)
const paginatedStreams = computed(() => {
  const start = (currentPage.value - 1) * pageSize
  const end = start + pageSize
  return streams.value.slice(start, end)
})

// 方法
const refreshData = async () => {
  loading.value = true
  try {
    await Promise.all([
      fetchStats(),
      fetchTaskCounts(),
      fetchStreams(),
      fetchWarnings()
    ])
  } finally {
    loading.value = false
  }
}

const fetchStats = async () => {
  try {
    const response = await api.get('/monitor/stats/')
    stats.value = response.data
  } catch (error) {
    console.error('获取统计信息失败:', error)
  }
}

const fetchTaskCounts = async () => {
  try {
    const response = await api.get('/tasks/list')
    
    // 响应数据已经是处理后的data字段
    let tasks = []
    if (response && response.items) {
      tasks = Array.isArray(response.items) ? response.items : []
    } else if (Array.isArray(response)) {
      // 兼容旧格式
      tasks = response
    }
    
    taskCounts.value = {
      recording: tasks.filter(task => task.type === 'recording').length,
      transcoding: tasks.filter(task => task.type === 'transcoding').length,
      segmenting: tasks.filter(task => task.type === 'segmenting').length,
      forwarding: tasks.filter(task => task.type === 'forwarding').length
    }
  } catch (error) {
    console.error('获取任务统计失败:', error)
  }
}

const fetchStreams = async () => {
  try {
    const response = await streamApi.getStreams()
    
    // 适配不同的API响应格式
    let streamsData = []
    if (response && response.items) {
      streamsData = Array.isArray(response.items) ? response.items : []
    } else if (Array.isArray(response)) {
      streamsData = response
    } else {
      streamsData = []
    }
    
    streams.value = streamsData
  } catch (error) {
    console.error('获取流列表失败:', error)
    streams.value = []
  }
}

const fetchWarnings = async () => {
  try {
    const response = await api.get('/monitor/warnings')
    warnings.value = response.data || []
  } catch (error) {
    console.error('获取警告信息失败:', error)
  }
}

const handlePageChange = (page) => {
  currentPage.value = page
}

const formatTime = (timestamp) => {
  return new Date(timestamp).toLocaleTimeString('zh-CN')
}

// 生命周期
onMounted(() => {
  refreshData()
  // 每30秒自动刷新
  setInterval(refreshData, 30000)
})
</script>

<style scoped>
.dashboard-container {
  padding: 24px;
  background: #f8fafc;
  min-height: 100vh;
}

/* 紧凑统计卡片样式 - 完全复制Streams.vue */
.stats-cards {
  margin-bottom: 24px;
}

.stats-cards.compact {
  margin-bottom: 16px;
}

.stat-card.compact {
  border-radius: 8px;
  box-shadow: 0 1px 3px rgba(0, 0, 0, 0.1);
  border: 1px solid #e5e7eb;
  background: white;
  transition: all 0.2s ease;
}

.stat-card.compact:hover {
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.15);
  transform: translateY(-1px);
}

.stat-content.compact {
  display: flex;
  align-items: center;
  gap: 8px;
}

.stat-icon.compact {
  font-size: 20px;
  color: #3b82f6;
}

.stat-number.compact {
  font-size: 18px;
  font-weight: 700;
  color: #1f2937;
  line-height: 1;
}

.stat-label.compact {
  font-size: 12px;
  color: #6b7280;
  line-height: 1;
}

/* 系统监控卡片 */
.system-grid {
  display: grid;
  grid-template-columns: 1fr 1fr;
  gap: 24px;
  margin-bottom: 24px;
}

.system-card {
  border-radius: 12px;
  box-shadow: 0 1px 3px rgba(0, 0, 0, 0.1);
  border: 1px solid #e5e7eb;
  background: white;
}

.card-title {
  display: flex;
  align-items: center;
  gap: 8px;
  font-size: 16px;
  font-weight: 600;
  color: #1f2937;
}

.service-status-list {
  display: flex;
  flex-direction: column;
  gap: 12px;
}

.service-item {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 12px 16px;
  background: #f9fafb;
  border-radius: 8px;
  transition: background 0.2s ease;
}

.service-item:hover {
  background: #f3f4f6;
}

.service-name {
  font-size: 14px;
  font-weight: 500;
  color: #374151;
}

.service-status {
  font-size: 12px;
  font-weight: 600;
  color: #10b981;
  padding: 4px 8px;
  background: #dcfce7;
  border-radius: 4px;
}

/* 直播墙样式 */
.stream-wall-card {
  border-radius: 12px;
  box-shadow: 0 1px 3px rgba(0, 0, 0, 0.1);
  border: 1px solid #e5e7eb;
  background: white;
}

.stream-grid {
  display: grid;
  grid-template-columns: repeat(4, 1fr);
  gap: 16px;
  margin-bottom: 20px;
}

.stream-item {
  position: relative;
  border-radius: 8px;
  overflow: hidden;
  box-shadow: 0 1px 3px rgba(0, 0, 0, 0.1);
  transition: all 0.2s ease;
  background: white;
}

.stream-item:hover {
  transform: translateY(-2px);
  box-shadow: 0 4px 12px rgba(0, 0, 0, 0.15);
}

.stream-preview {
  position: relative;
  width: 100%;
  padding-bottom: 56.25%;
  overflow: hidden;
}

.stream-image {
  position: absolute;
  top: 0;
  left: 0;
  width: 100%;
  height: 100%;
  object-fit: cover;
  border-radius: 8px;
}

.stream-status-badge {
  position: absolute;
  top: 8px;
  right: 8px;
  padding: 4px 8px;
  border-radius: 4px;
  font-size: 12px;
  font-weight: 600;
  color: white;
  backdrop-filter: blur(4px);
}

.stream-status-badge.online {
  background: rgba(16, 185, 129, 0.9);
}

.stream-status-badge.offline {
  background: rgba(239, 68, 68, 0.9);
}

.pagination-container {
  display: flex;
  justify-content: center;
  margin-top: 20px;
}

/* 警告列表样式 */
.warning-list {
  max-height: 200px;
  overflow-y: auto;
}

.no-warning {
  text-align: center;
  padding: 40px 0;
  color: #6b7280;
}

.warning-item {
  padding: 12px 0;
  border-bottom: 1px solid #f3f4f6;
}

.warning-item:last-child {
  border-bottom: none;
}

.warning-time {
  font-size: 12px;
  color: #6b7280;
  margin-bottom: 4px;
}

.warning-message {
  font-size: 14px;
  color: #ef4444;
}

/* 响应式设计 */
@media (max-width: 1200px) {
  .stream-grid {
    grid-template-columns: repeat(3, 1fr);
  }
}

@media (max-width: 768px) {
  .dashboard-container {
    padding: 16px;
  }
  
  .system-grid {
    grid-template-columns: 1fr;
  }
  
  .stream-grid {
    grid-template-columns: repeat(2, 1fr);
  }
}

@media (max-width: 480px) {
  .stream-grid {
    grid-template-columns: 1fr;
  }
}
</style>